import { useState } from 'react'
import { connect } from 'react-redux'
import { useRouteMatch } from 'react-router-dom'

function User({ users, dispatch }) {
  const {
    params: { id },
  } = useRouteMatch()

  const [newUserName, setNewUserName] = useState('')

  const actualUser = users.find(user => user.id === id)

  function updateUserHandler() {
    dispatch({
      type: 'update_user',
      payload: {
        user: {
          ...actualUser,
          name: newUserName,
        },
      },
    })
  }

  return (
    <div className="user page">
      This is user {actualUser.name} 's page
      <input
        value={newUserName}
        onChange={e => setNewUserName(e.target.value)}
      />
      <button onClick={updateUserHandler}>更新用户姓名</button>
    </div>
  )
}

export default connect(({ users }) => ({ users }))(User)
